package cc.avatar.util;

import java.io.File;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;

public class DataTransferTool {
	private String password;
	private String databaseName;
	private String targetPath = "";
	private String filenamePrefix = "data";
	private ScriptRunner runner = new ScriptRunner();
	private final static DateFormat TIMEFORMAT = new java.text.SimpleDateFormat(
			"yyyyMMdd-HH_mm");

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setTargetPath(String targetPath) {
		this.targetPath = targetPath;
	}

	public String export2sql() {
		StringBuilder command = new StringBuilder("mysqldump.exe -uroot -p");
		command.append(password).append(" --opt -t --replace ").append(
				databaseName);
		command.append(" > ").append(this.targetPath);
		String filename = filenamePrefix + TIMEFORMAT.format(new Date())
				+ ".sql";
		command.append(filename);
		runner.executeScript(new String[] {command.toString()});
		return filename;
	}

	// 热恢复 -仅数据
	private String load(String filename) {
		String command = "mysql.exe " + this.databaseName + " < " + this.targetPath + filename + " -uroot -p" + this.password;
		runner.executeScript(new String[] {command.toString()});
		return "数据导入成功。";
	}
	
	//在default folder中找最新的sql文件自动载入
	public String importLatestData(){
		File file = this.getLatestFileByName(new File(this.targetPath));
		if (file == null) return "";
		String filename = file.getName();
		load(filename);
		return filename;
	}
	
	 public File getLatestFileByName(File dirFile) {  
	     assert dirFile.isDirectory();   
         File[] files = dirFile.listFiles(new ExtensionFileFilter("sql"));
         if (files == null || files.length == 0)
        	 return null;
         FileWrapper [] fileWrappers = new FileWrapper[files.length];  
         for (int i=0; i<files.length; i++) {  
             fileWrappers[i] = new FileWrapper(files[i]);  
         }           
         Arrays.sort(fileWrappers);  
         return fileWrappers[fileWrappers.length - 1].getFile();  
     }  	
}

@SuppressWarnings("unchecked")
class FileWrapper implements Comparable {   
    private File file;  
      
    public FileWrapper(File file) {  
        this.file = file;  
    }  
       
	public int compareTo(Object obj) {  
	    assert obj instanceof FileWrapper;            
	    FileWrapper castObj = (FileWrapper)obj;                     
	    if (this.file.getName().compareTo(castObj.getFile().getName()) > 0) {  
	        return 1;  
	    } else if (this.file.getName().compareTo(castObj.getFile().getName()) < 0) {  
	        return -1;  
	    } else {  
	        return 0;  
	    }  
	}    
	      
	public File getFile() {  
	    return this.file;  
	}  
}
